import { Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
let wsUrl = `${process.env.VUE_APP_ORIGIN_API}messageService/websocket/message`

var websocket = null

// 获取websocket
export function getWebsocket() {
  return websocket
}

// 初始化websocket
export function initWebSocket(onmessage, onerror) {
  if (typeof WebSocket === 'undefined') {
    Message({
      type: 'error',
      message: 'websocket不支持!',
      showClose: true,
    })
    return false
  }
  if (websocket) {
    return
  }
  // ws请求完整地址
  const requstWsUrl = `${wsUrl}`
  // 创建websocket实例
  websocket = new WebSocket(requstWsUrl, getToken())
  // 接收消息
  websocket.onmessage = function (e) {
    onmessage(e)
  }
  // 错误
  websocket.onerror = function (e) {
    Message({
      type: 'error',
      message: 'websocket连接关闭',
      showClose: true,
    })
    console.log(e)
    onerror(e)
  }
  // 关闭
  websocket.onclose = function (e) {
    count++
    console.log(e)
    console.log(`websocket连接关闭!正在重连${count}次...`)
    websocket = null
    var time = setTimeout(() => {
      // 断线重连
      initWebSocket(onmessage, onerror)
    }, 1000)
    if (count >= 10) {
      Message({
        type: 'warning',
        message: `websocket连接关闭!正在重连${count}次...`,
        showClose: true,
      })
      clearTimeout(time)
      store.dispatch('user/logout')
      return false
    }
  }
}
